package com.zpark.controller;

import com.zpark.pojo.User;
import com.zpark.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(path = "addUser", method = RequestMethod.POST)
    @ResponseBody
    public void addUser(@RequestBody User user) {
        userRepository.save(user);
    }

    @RequestMapping(path = "deleteUser", method = RequestMethod.POST)
    @ResponseBody
    public void deleteUser(@RequestBody User user) {
        userRepository.delete(user);
    }

    @RequestMapping(path = "/getById/{id}", method = RequestMethod.GET)
    @ResponseBody
    public User queryUserById(@PathVariable("id") int id) {
        return userRepository.findById(id).orElse(null);
    }

    @RequestMapping(path = "/getByName/{name}", method = RequestMethod.GET)
    @ResponseBody
    public User queryUserByName(@PathVariable("name") String name) {
        Optional<User> optional = userRepository.findByName(name);
        return optional.orElse(null);
    }
}